/**
 * unPlarer-Youtube 0.8.0 
 *
 * @author Alvaro Lopez, Juan Baquero
 * 
 * http://code.google.com/p/unplayer-youtube/
 **/

package unplayer.youtubeplayer.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
public class HttpConnection extends Thread {
	
	public HttpConnection(UrlStream st,String u,int si)
	{
		url = u;
		caller = st;
		size = si;
	}
	
	public void run()
	{
		int indexId;
		String videoId;	
		String videoWebUrl=null;
		String videoInfoCode;
		
		String title = "";
		
		int indexStreamMap;
		String videoStreamMap;
		
		int error = UrlStream.OK;
		
	    URL newUrl = null;
	    InputStreamReader isReader = null;
	    BufferedReader bReader = null;
	    String lineUrl;
	    StringBuffer bufferInfo = new StringBuffer();
	    
		//GUARDANOS EL ID DE LA DIRECCION
		indexId = url.indexOf("v=");
		indexId=indexId+2;
		videoId = url.substring(indexId, indexId+sizeId+1);
		
		//HASHMAPS CON LOS STREAMS
		HashMap<Integer, String> streams;

	    try {  
		      newUrl = new URL("http://www.youtube.com/get_video_info?video_id="+videoId);
		      isReader = new InputStreamReader(newUrl.openStream());
		      bReader = new BufferedReader(isReader);
		      while ((lineUrl = bReader.readLine()) != null){
		    	  bufferInfo.append(lineUrl);
		      }
		      bReader.close();
		      isReader.close();
		      
	    } catch (MalformedURLException e) {
		      //e.printStackTrace();
		      error=UrlStream.URL_ERROR;
		} catch (IOException e) {
		      //e.printStackTrace();
		      error=UrlStream.NO_CONNECTION;
		} 
		
		if(error!=UrlStream.OK) 
		{
			caller.setUrlStream(videoWebUrl, title,error);
			return;
		}
		
	      
		try {
			
		    //GUARDAMOS EL CODIGO DE LA PAGINA
			
			int indexStream1;
			int indexStream2;
			int key;
			
			videoInfoCode=bufferInfo.toString();
			
			//GUARDAMOS EL MAP_STRING
			
			indexStreamMap = videoInfoCode.indexOf("fmt_stream_map=");
			if(indexStreamMap<0)
			{
				videoSpecial();
				return;
			}
			
			videoStreamMap = videoInfoCode.substring(indexStreamMap+15, videoInfoCode.indexOf("&", indexStreamMap));
			videoStreamMap = URLDecoder.decode(videoStreamMap, "UTF-8");

			
			//BUSQUEDA DE CADA STREAM
			
			streams = new HashMap<Integer, String>();
			
			indexStream1 = 0;
			
			while(indexStream1!=-1)
			{	
				indexStream2 = videoStreamMap.indexOf("|",indexStream1);
				
				if(indexStream1==0) indexStream1=-1; //CASO INICIAL DONDE NO HAY ","
				
				key = Integer.parseInt(videoStreamMap.substring(indexStream1+1,indexStream2));
				
				indexStream1 = videoStreamMap.indexOf("||",indexStream2);
				
				streams.put(key, videoStreamMap.substring(indexStream2+1,indexStream1));
				
				indexStream1 = videoStreamMap.indexOf(",",indexStream1);
			}
			
			//OBTENEMOS EL VIDEO POR TAMANYO
			
			if(size==0)
			{
				videoWebUrl = streams.get(35);
				
				if(videoWebUrl==null) 
					videoWebUrl = streams.get(34);
				
				if(videoWebUrl==null) 
					videoWebUrl = streams.get(5);
			}else
			{
				videoWebUrl = streams.get(size);
			}
			
			if(videoWebUrl==null)
				error=UrlStream.NO_SIZE;
			
			
			//TITULO
			
			indexStream1 = videoInfoCode.indexOf("title=");
			indexStream2 = videoInfoCode.indexOf("&",indexStream1);
			if(indexStream2==-1)indexStream2=videoInfoCode.length();
			title = videoInfoCode.substring(indexStream1+6,indexStream2);			
			title = URLDecoder.decode(title, "UTF-8");
			title = title.replace('+', ' ');
			title = "YouTube  -  "+title;
			
		}catch (Exception e) {
			 //e.printStackTrace();
		     error=UrlStream.NO_VIDEO;
		}

	    caller.setUrlStream(videoWebUrl, title,error);
	}
	
	private void videoSpecial()
	{
		String videoWebUrl=null;
		String videoWebCode;
		
		String title = "";
		
		int indexStreamMap;
		String videoStreamMap;
		
		int error = UrlStream.OK;
		
	    URL newUrl = null;
	    InputStreamReader isReader = null;
	    BufferedReader bReader = null;
	    String lineUrl;
	    StringBuffer bufferPage = new StringBuffer();
		
		//HASHMAPS CON LOS STREAMS
		HashMap<Integer, String> streams;

	    try {
	    	
		      newUrl = new URL(url);
		      isReader = new InputStreamReader(newUrl.openStream());
		      bReader = new BufferedReader(isReader);
		      while ((lineUrl = bReader.readLine()) != null){
		    	  bufferPage.append(lineUrl);
		      }
		      bReader.close();
		      isReader.close();
		      
	    } catch (MalformedURLException e) {
		      //e.printStackTrace();
		      error=UrlStream.URL_ERROR;
		} catch (IOException e) {
		      //e.printStackTrace();
		      error=UrlStream.NO_CONNECTION;
		} 
		
		if(error!=UrlStream.OK) 
		{
			caller.setUrlStream(videoWebUrl, title,error);
			return;
		}
		
	      
		try {
			
		    //GUARDAMOS EL CODIGO DE LA PAGINA
			videoWebCode =bufferPage.toString();
			
			int indexStream1;
			int indexStream2;
			int key;
			
			//GUARDAMOS EL MAP_STRING
			
			indexStreamMap = videoWebCode.indexOf("fmt_stream_map=");
			videoStreamMap = videoWebCode.substring(indexStreamMap+15, videoWebCode.indexOf("&", indexStreamMap));
			videoStreamMap = URLDecoder.decode(videoStreamMap, "UTF-8");

			if(indexStreamMap==-1) throw new Exception("No video");
			
			//BUSQUEDA DE CADA STREAM
			
			streams = new HashMap<Integer, String>();
			
			indexStream1 = 0;
			
			while(indexStream1!=-1)
			{	
				indexStream2 = videoStreamMap.indexOf("|",indexStream1);
				
				if(indexStream1==0) indexStream1=-1; //CASO INICIAL DONDE NO HAY ","
				
				key = Integer.parseInt(videoStreamMap.substring(indexStream1+1,indexStream2));
				
				indexStream1 = videoStreamMap.indexOf("||",indexStream2);
				
				streams.put(key, videoStreamMap.substring(indexStream2+1,indexStream1));
				
				indexStream1 = videoStreamMap.indexOf(",",indexStream1);
			}
			
			//OBTENEMOS EL VIDEO POR TAMANYO
			
			if(size==0)
			{
				videoWebUrl = streams.get(35);
				
				if(videoWebUrl==null) 
					videoWebUrl = streams.get(34);
				
				if(videoWebUrl==null) 
					videoWebUrl = streams.get(5);
			}else
			{
				videoWebUrl = streams.get(size);
			}

			if(videoWebUrl==null)
				error=UrlStream.NO_SIZE;
			
			//TITULO
			
			int inTit1 = videoWebCode.indexOf("<title>");
			int inTit2 = videoWebCode.indexOf("</title>");;
			
			title = videoWebCode.substring(inTit1+7, inTit2);
			title = "YouTube  -  "+title.substring(14);
			
		}catch (Exception e) {
			 //e.printStackTrace();
		     error=UrlStream.NO_VIDEO;
		}

	    caller.setUrlStream(videoWebUrl, title,error);
	}
	

	private String url;
	private int sizeId = 10;
	private int size;
	UrlStream caller;
}



